package nodeServer

import (
	"awesomeTask/application/variable"
	"awesomeTask/commom/KeyHelper"
	"awesomeTask/commom/MessageHelper"
	event2 "awesomeTask/system/event"
	"awesomeTask/system/helper"
	log2 "awesomeTask/system/log"
	TcpServer "awesomeTask/system/tcpServer/tcpServer"
	"fmt"
	"net"
	"sync"
)

var currentRunningNodeConnections sync.Map

func RunAsNodeServer(listenPort float64) {
	server := TcpServer.TcpServer{}
	server.OnConnect(func(connection net.Conn) {
		currentRunningNodeConnections.Store(KeyHelper.TcpUniqueIdByConnection(connection), connection)
	})
	server.OnMessage(func(connection net.Conn, message string) {
		defer func() {
			if r := recover(); r != nil {
				log2.GetLogger().Error("无法解析的数据:" + message)
			}
		}()
		info := helper.JsonDecode(message)
		if value, ok := variable.TaskServerEvent[info.(map[string]interface{})["event"].(string)]; ok {
			if info.(map[string]interface{})["event"].(string) == variable.ON_TASK_NODE_REMOTE_FORK {
				info.(map[string]interface{})["pTaskId"] = KeyHelper.TcpUniqueIdByConnection(connection)
			}
			event2.Dispatch(value, info)
		}
		if info.(map[string]interface{})["event"] != nil && info.(map[string]interface{})["event"] == variable.ON_TASK_NODE_RESULT {
			event2.Dispatch(info.(map[string]interface{})["uniqueTaskId"].(string), info)
		}

	})
	server.OnClose(func(conn net.Conn) {
		currentRunningNodeConnections.Delete(KeyHelper.TcpUniqueIdByConnection(conn))
	})
	server.OnError(func(err error) {

	})
	server.Start(int(listenPort), true)
}

/**
发送数据给正在运行的node进程
*/
func SendToTaskNode(pTaskId string, event string, message map[string]interface{}) {
	if con, ok := currentRunningNodeConnections.Load(pTaskId); ok {
		fmt.Println("发送成功")
		MessageHelper.SendEvent(event, message, con.(net.Conn))
	} else {
		fmt.Println("node断开连接")
	}
}
